package com.example.lab3.Impl;


import com.example.lab3.Entity.DataModel;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


@Repository
public class getDataImpl {

    @javax.annotation.Resource(name = "爬取数据辅助类")
    private RestTemplate restTemplate;

    /**
     * 从gitee中获取数据并化成输入数据流
    * */
    public InputStream getDataInputStream() throws IOException  {
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create("https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> responseEntity = restTemplate.exchange(requestEntity, Resource.class);
        Resource body = responseEntity.getBody();
        assert body!=null;
        return body.getInputStream();
    }

    /**
     * 将输入数据流写入类中
     * @Scheduled 用于自动更新
     *
     * */
    private List<DataModel> dataModels = new ArrayList<>();
    public String dataTime = new String();
    @Scheduled(cron = "0 0 1 * * *")
    @PostConstruct
    public void getData() throws IOException {
        //将输入流化成csv 官方文档：https://commons.apache.org/proper/commons-csv/user-guide.html
        Reader in = new InputStreamReader(getDataInputStream(), StandardCharsets.UTF_8);
        Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
        /**
         * 获取最新日期
         * 将数据放入List中
         * @最新日期dataTime
         * */
        try {
            for (final CSVRecord record : records) {
                /**
                 * recordNumber==1是为表头,用来获取最新日期
                 * 从2开始就是数据
                 * */
                if (record.getRecordNumber() == 1) {
                    //日期格式:日/月/年 例11/29/20
                    String[] perTime = record.get(record.size() - 1).split("/");
                    dataTime = "20" + perTime[2] + "年" + perTime[0] + "月" + perTime[1] + "日";
                } else {
                    DataModel dataModel = new DataModel();
                    dataModel.setCountry(record.get(1));
                    dataModel.setState(record.get(0));
                    dataModel.setLatestTotalCases(Integer.parseInt(record.get(record.size() - 1)));
                    dataModel.setDiffFromPrevDay(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)));
                    dataModels.add(dataModel);
                }
            }
        } finally {
            Collections.sort(dataModels, new Comparator<DataModel>() {
                @Override
                public int compare(DataModel o1, DataModel o2) {
                    return o2.getLatestTotalCases() - o1.getLatestTotalCases();
                }
            });
        }
    }

    public List<DataModel> getSortData(){
        System.out.println(dataModels);
        return dataModels;
    }
    public List<DataModel> searchDataModel(String address){
        if (address=="")return dataModels;
        List<DataModel> dataModelsBySearch = new ArrayList<>();
        for(DataModel dataModel : dataModels){
            if(dataModel.getCountry().equals(address)||dataModel.getState().equals(address))
                dataModelsBySearch.add(dataModel);
        }
        return dataModelsBySearch;
    }

}
